const sqlite3 = require('sqlite3').verbose();
const axios = require('axios');

const db = new sqlite3.Database('L:/AI/chatgpt/one-api/one-api.db');
/**
CREATE TABLE `channels` (
    `id` INTEGER,
    `type` INTEGER DEFAULT 0,
    `key` text,
    `status` INTEGER DEFAULT 1,
    `name` text,
    `weight` INTEGER DEFAULT 0,
    `created_time` INTEGER,
    `test_time` INTEGER,
    `response_time` INTEGER,
    `base_url` text DEFAULT "",
    `other` text,
    `balance` REAL,
    `balance_updated_time` INTEGER,
    `models` text,
    `group` VARCHAR ( 32 ) DEFAULT "default",
    `used_quota` INTEGER DEFAULT 0,
    `model_mapping` VARCHAR ( 1024 ) DEFAULT "",
    `priority` INTEGER DEFAULT 0,
    `config` text,
    PRIMARY KEY ( `id` ) 
    );
 */
work();
var testUrl = ['https://api.smnet1.asia'];
testUrl = [];
async function work() {
  try {
    // 使用 `all` 方法来获取所有查询结果
    let rows = await new Promise((resolve, reject) => {
      db.all("SELECT id, name, base_url, models, key, status FROM channels", (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });

    // 同步遍历每一行结果
    for (let row of rows) {
      if(row.status != 1) {
        continue;
      }
      var url = row.base_url;
      console.log(row.name + ": " + url, row.key);
      // 更新模型
      if (testUrl.length > 0) {
        if (testUrl.includes(url)) {
          await updateData(url, row.key, row.id);
        }

      } else {
        await updateData(url, row.key, row.id);
      }
    }

  } catch (error) {
    console.error("An error occurred:", error);
  } finally {
    // 关闭数据库连接
    db.close();
  }
}

async function updateData(url, sk, id) {
  var data = await getModels(url, sk);
  if (data == null) {
    return
  }
  //取模型
  var models = [];
  for (let item of data) {
    var model = item.id;
    if (model) {
      models.push(model);
    }
  }
  if (models.length > 0) {
    var newData = models.join(', ');
    console.log(url, 'newData', newData);
    db.run(`UPDATE channels SET models = ? WHERE id = ?`, [newData, id], function (err) {
      if (err) {
        console.error(err.message);
      } else {
        console.log(`Row updated successfully`);
      }
    });
  }
}
async function getModels(url, sk) {
  const postData = {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + sk
    }
  }
  try {
    const response = await axios.get(url + '/v1/models', postData);
    var data = response.data;
    if (response.status == 200 && data.data) {
      console.log(url + '-data.length', data.data.length, typeof (data.data));
      return data.data
    }
  } catch (error) {
    console.error('error', url);
  }
  return null
}